package com.samphanie.auiu.gateway.filter;

import com.samphanie.auiu.common.constants.AuiuConstants;
import com.samphanie.auiu.gateway.config.IgnoreUrlsConfig;
import lombok.RequiredArgsConstructor;
import lombok.val;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.net.URI;


/**
 * 白名单路径访问时需要移除JWT请求头
 *
 * @author ZSY
 * @email 1451691457@qq.com
 */
@Component
@RequiredArgsConstructor
public class IgnoreUrlsRemoveJwtFilter implements WebFilter {
    private final IgnoreUrlsConfig ignoreUrlsConfig;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange,@NonNull WebFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        URI uri = request.getURI();
        val pathMatcher = new AntPathMatcher();
        // 白名单路径移除JWT请求头
        val ignoreUrls = ignoreUrlsConfig.getUrls();

        for (String ignoreUrl : ignoreUrls) {
            if (pathMatcher.match(ignoreUrl, uri.getPath())) {
                request = exchange.getRequest().mutate().header(AuiuConstants.JWT_TOKEN_HEADER, "").build();
                exchange = exchange.mutate().request(request).build();
                return chain.filter(exchange);
            }
        }

        return chain.filter(exchange);
    }
}
